package cn.rkylin.oms.warehouse.local.returnStockin.controller;

import java.net.URLDecoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;

import cn.rkylin.core.controller.ApolloController;
import cn.rkylin.oms.common.annotation.SystemControllerLog;
import cn.rkylin.oms.common.consts.LocalReturnStockinStatus;
import cn.rkylin.oms.common.context.CurrentUser;
import cn.rkylin.oms.common.context.WebContextFactory;
import cn.rkylin.oms.common.dto.DBLog;
import cn.rkylin.oms.common.utils.LogUtil;
import cn.rkylin.oms.warehouse.local.returnStockin.dao.ReturnStockinDAOImpl;
import cn.rkylin.oms.warehouse.local.returnStockin.dao.ReturnStockinSkuDAOImpl;
import cn.rkylin.oms.warehouse.local.returnStockin.service.IReturnStockinService;
import cn.rkylin.oms.warehouse.local.returnStockin.vo.ReturnStockinSkuVO;
import cn.rkylin.oms.warehouse.local.returnStockin.vo.ReturnStockinVO;

/**
 * 本地库退货入库单Controller
 * 
 * @author 齐涛
 * @version 1.0
 * @created 28-9-2017 10:51:30
 */
@Controller
@RequestMapping("/localReturnStockin")
public class LocalReturnStockinController extends ApolloController {

	private static final Log logger = LogFactory.getLog(LocalReturnStockinController.class);
	private static final String PAGE_SELECT_STATEMENT = "pageSelectLocalReturnStockin";
	private static final String PAGE_SUK_SELECT_STATEMENT = "selectLocalReturnStockinSkuList";

	@Autowired
	private IReturnStockinService returnStockinServiceImpl;

	@Autowired
	private LogUtil logUtil;

	/**
	 * 查询本地库退货入库单列表
	 * 
	 * @param quickSearch
	 *            快速查询条件
	 * @param formJson
	 *            高级检索条件
	 * @param param
	 *            本地库退货入库单VO
	 * @param start
	 *            第几页
	 * @param length
	 *            每页多少行
	 * @return 结果Map
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@ResponseBody
	@RequestMapping(value = "/getReturnStockinList")
	public Map<String, Object> getReturnStockinList(String quickSearch, String formJson, String returnStockinStatus,
			@RequestParam(required = false, defaultValue = "0") int start,
			@RequestParam(required = false, defaultValue = "10") int length) {
		Map map = new HashMap();
		try {
			// 处理分页
			if (length == -1) {
				length = Integer.MAX_VALUE;
			}
			int page = start / length + 1;

			ReturnStockinVO param = new ReturnStockinVO();
			// 高级查询检索条件
			formJson = URLDecoder.decode(formJson, "UTF-8");
			JSONObject jsonObject = JSONObject.parseObject(formJson);
			param.setStorId((String) jsonObject.get("storId"));
			param.setShopId((String) jsonObject.get("shopId"));
			param.setKind((String) jsonObject.get("kind"));
			param.setCreateTimeStart((String) jsonObject.get("createTimeStart"));
			param.setCreateTimeEnd((String) jsonObject.get("createTimeEnd"));
			param.setFactInTimeStart((String) jsonObject.get("factInTimeStart"));
			param.setFactInTimeEnd((String) jsonObject.get("factInTimeEnd"));
			param.setFinishTimeStart((String) jsonObject.get("finishTimeStart"));
			param.setFinishTimeEnd((String) jsonObject.get("finishTimeEnd"));
			param.setSkuCode((String) jsonObject.get("skuCode"));
			param.setSkuName((String) jsonObject.get("skuName"));
			param.setGoodsCode((String) jsonObject.get("goodsCode"));
			param.setGoodsName((String) jsonObject.get("goodsName"));
			// 快速查询检索条件
			quickSearch = URLDecoder.decode(quickSearch, "UTF-8");
			if (StringUtils.isNotEmpty(quickSearch)) {
				param.setQuickSearch(quickSearch);
			}
			param.setReturnStockinStatus(returnStockinStatus);
			// 设置项目Id
			CurrentUser currentUser = WebContextFactory.getWebContext().getCurrentUser();
			String prjId = currentUser.getCurrentProject().getPrjId();
			param.setPrjId(prjId);

			// 处理转义的字段
			Map<String, String> replaceFieldsMap = new HashMap<String, String>();
			replaceFieldsMap.put("enableStatus", "enable");

			// 排序语句生成
			String orderStatement = getOrderString(ReturnStockinDAOImpl.class.getName(), PAGE_SELECT_STATEMENT,
					replaceFieldsMap);
			if (StringUtils.isNotEmpty(orderStatement)) {
				param.setOrderBy(orderStatement);
			}

			PageInfo<ReturnStockinVO> stockInList = returnStockinServiceImpl.findByWhere(page, length, param);
			map.put(JSON_RESULT, SUCCESS);
			map.put(RECORDS_FILTERED, stockInList.getTotal());
			map.put(RECORDS_TOTAL, stockInList.getTotal());
			map.put(RETURN_DATA, stockInList.getList());

		} catch (Exception ex) {
			logUtil.error(ex.getMessage(), ex);
			map.put(JSON_RESULT, FAILED);
			map.put(JSON_MSG, ex.getMessage());
		}

		return map;
	}

	/**
	 * 查询本地库退货入库单列表数量
	 *
	 * @param quickSearch
	 *            快速查询条件
	 * @param formJson
	 *            高级检索条件
	 * @param param
	 *            本地库退货入库单VO
	 * @param start
	 *            第几页
	 * @param length
	 *            每页多少行
	 * @return 结果Map
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@ResponseBody
	@RequestMapping(value = "/getReturnStockinListCount")
	public Map<String, Object> getReturnStockinListCount(String quickSearch, String formJson, String eturnStockinStatus,
			@RequestParam(required = false, defaultValue = "0") int start,
			@RequestParam(required = false, defaultValue = "10") int length) {
		Map map = new HashMap();
		try {
			// Map waitReceiveMap = this.getReturnStockinList(quickSearch, formJson,
			// ReturnStockinStatus.WAIT_RECEIVE, start, length);
			Map receivingMap = this.getReturnStockinList(quickSearch, formJson, LocalReturnStockinStatus.RECEIVING,
					start, length);
			Map completeMap = this.getReturnStockinList(quickSearch, formJson, LocalReturnStockinStatus.COMPLETE, start,
					length);
			Map canceledMap = this.getReturnStockinList(quickSearch, formJson, LocalReturnStockinStatus.CANCELED, start,
					length);

			map.put(JSON_RESULT, SUCCESS);
			// map.put("waitReceiveCount", waitReceiveMap.get(RECORDS_TOTAL));
			map.put("receivingCount", receivingMap.get(RECORDS_TOTAL));
			map.put("completeCount", completeMap.get(RECORDS_TOTAL));
			map.put("canceledCount", canceledMap.get(RECORDS_TOTAL));

		} catch (Exception ex) {
			logUtil.error(ex.getMessage(), ex);
			map.put(JSON_RESULT, FAILED);
			map.put(JSON_MSG, ex.getMessage());
		}

		return map;
	}

	/**
	 * 查询本地库退货入库单信息
	 *
	 * @param stockinId
	 *            本地库退货入库单Id
	 * @return 结果Map
	 * @throws Exception
	 *             异常
	 */
	@ResponseBody
	@RequestMapping(value = { "/getReturnStockInInfo/{stockinId}" })
	public Map<String, Object> getReturnStockInInfo(@PathVariable String stockinId) {
		Map<String, Object> returnMap = new HashMap<String, Object>();
		try {
			ReturnStockinVO returnStockInVO = new ReturnStockinVO();
			returnStockInVO.setStockinId(stockinId);
			ReturnStockinVO data = returnStockinServiceImpl.getReturnStockinInfo(returnStockInVO);

			returnMap.put(JSON_RESULT, SUCCESS);
			returnMap.put(RETURN_DATA, data);
		} catch (Exception ex) {
			logUtil.error(ex.getMessage(), ex);
			returnMap.put(JSON_RESULT, FAILED);
			returnMap.put(JSON_MSG, ex.getMessage());
		}

		return returnMap;
	}

	/**
	 * 查询本地库退货入库单商品列表
	 *
	 * @param shiporderId
	 *            本地库退货入库单Id
	 * @return 结果Map
	 */
	@ResponseBody
	@RequestMapping(value = "/getReturnStockInSkuList")
	public Map<String, Object> getReturnStockInSkuList(String stockinId, String kind) {
		Map<String, Object> returnMap = new HashMap<String, Object>();

		try {
			ReturnStockinSkuVO returnStockinSkuVO = new ReturnStockinSkuVO();
			returnStockinSkuVO.setStockinId(stockinId);
			returnStockinSkuVO.setKind(kind);
			// 处理转义的字段
			Map<String, String> replaceFieldsMap = new HashMap<String, String>();
			// 排序语句生成
			String orderStatement = getOrderString(ReturnStockinSkuDAOImpl.class.getName(), PAGE_SUK_SELECT_STATEMENT,
					replaceFieldsMap);
			if (StringUtils.isNotEmpty(orderStatement)) {
				returnStockinSkuVO.setOrderBy(orderStatement);
			}

			List<ReturnStockinSkuVO> returnStockInSkuVOList = returnStockinServiceImpl
					.selectReturnStockinSkuList(returnStockinSkuVO);

			returnMap.put(JSON_RESULT, SUCCESS);
			returnMap.put(RETURN_DATA, returnStockInSkuVOList);
		} catch (Exception ex) {
			logUtil.error(ex.getMessage(), ex);
			returnMap.put(JSON_RESULT, FAILED);
			returnMap.put(JSON_MSG, ex.getMessage());
		}

		return returnMap;
	}

	/**
	 * 修改本地库退货入库单
	 * 
	 * @param returnStockInVO
	 *            本地库退货入库单VO
	 * @return 结果Map
	 */
	@ResponseBody
	@RequestMapping(value = "/updateReturnStockIn")
	@SystemControllerLog(module = "本地库退货入库单", operation = "修改本地库退货入库单", keyCode = "stockinId")
	public Map<String, Object> updateReturnStockIn(@RequestBody ReturnStockinVO returnStockinVO) {
		Map<String, Object> returnMap = new HashMap<String, Object>();

		try {
			returnStockinServiceImpl.updateReturnStockin(returnStockinVO);

			logUtil.info(new DBLog(returnStockinVO.getStockinCode(), "修改本地库退货入库单", "本地库退货入库单管理", "修改成功"));

			returnMap.put(JSON_RESULT, SUCCESS);
		} catch (Exception ex) {
			logUtil.error(new DBLog(returnStockinVO.getStockinCode(), "修改退货入库单", "退货入库单管理", ex.getMessage()));
			logger.error(ex.getMessage(), ex);
			returnMap.put(JSON_RESULT, FAILED);
			returnMap.put(JSON_MSG, ex.getMessage());
		}
		returnMap.put("stockinId", returnStockinVO.getStockinId());
		return returnMap;
	}

	/**
	 * 取消本地库退货入库单̬
	 *
	 * @param stockinId
	 *            本地库退货入库单Id
	 * @return 结果Map
	 */
	@ResponseBody
	@RequestMapping(value = { "/cancelReturnStockin/{stockinId}" })
	@SystemControllerLog(module = "本地库退货入库单", operation = "取消本地库退货入库单", keyCode = "stockinId")
	public Map<String, Object> cancelReturnStockin(@PathVariable String stockinId) {
		Map<String, Object> returnMap = new HashMap<String, Object>();

		try {
			Map<String, String> resultMap = returnStockinServiceImpl.cancelReturnStockin(stockinId);

			logUtil.info(new DBLog(stockinId, "取消本地库退货入库单", "本地库退货入库单管理", "取消成功"));

			if ("true".equals(resultMap.get("success"))) {
				returnMap.put(JSON_RESULT, SUCCESS);
				returnMap.put(RETURN_DATA, "取消成功");
			} else {
				returnMap.put(JSON_RESULT, FAILED);
				returnMap.put(JSON_MSG, "取消失败");
			}
		} catch (Exception ex) {
			logUtil.error(new DBLog(stockinId, "取消本地库退货入库单", "本地库退货入库单管理", ex.getMessage()));
			logUtil.error(ex.getMessage(), ex);
			returnMap.put(JSON_RESULT, FAILED);
			returnMap.put(JSON_MSG, ex.getMessage());
		}
		returnMap.put("stockinId", stockinId);
		return returnMap;
	}

	/**
	 * 完成入库单
	 *
	 * @param stockInVO
	 *            入库单VO
	 */
	@ResponseBody
	@RequestMapping(value = "/finishStockIn")
	@SystemControllerLog(module = "入库单管理", operation = "完成入库单", keyCode = "stockinId")
	public Map<String, Object> finishStockIn(@RequestBody ReturnStockinVO stockInVO) {
		Map<String, Object> returnMap = new HashMap<String, Object>();

		try {
			// 设置入库商品信息
			List<ReturnStockinSkuVO> list = stockInVO.getReturnStockinSkuVOList();
			for (int i = 0; i < list.size(); i++) {
				ReturnStockinSkuVO returnStockinSkuVO = (ReturnStockinSkuVO) list.get(i);
				String stockinSkuId = java.util.UUID.randomUUID().toString().replace("-", "");
				returnStockinSkuVO.setStockinSkuId(stockinSkuId);
			}

			// 完成入库单
			returnStockinServiceImpl.updateFinishStockIn(stockInVO);

			logUtil.info(new DBLog(stockInVO.getStockinCode(), "完成入库单", "入库单管理", "完成成功"));

			returnMap.put(JSON_RESULT, SUCCESS);
		} catch (Exception ex) {
			logUtil.error(new DBLog(stockInVO.getStockinCode(), "完成入库单", "入库单管理", ex.getMessage()));
			logger.error(ex.getMessage(), ex);
			returnMap.put(JSON_RESULT, FAILED);
			returnMap.put(JSON_MSG, ex.getMessage());
		}
		returnMap.put("stockinId", stockInVO.getStockinId());
		return returnMap;
	}

}
